#include "tabmanager.h"
#include "../gui/tabscreen.h"
#include "../gui/interfaces.h"

#include <QSettings>
#include <QDebug>

TabManager::TabManager( TabScreen * tabScreen, PluginHandler * handler ) {
    this->mTabScreen = tabScreen;
    this->mPluginHandler = handler;
}

void TabManager::addTab( WhaleTabBase * tab ) {
    this->mActiveTabs.push_back( tab );
    this->mTabScreen->addTab( tab );
    connect( tab, SIGNAL( closed() ), this, SLOT( tabClosed() ) );
}

void TabManager::tabClosed() {
    WhaleTabBase * tab = qobject_cast< WhaleTabBase * >( sender() );
    this->mTabScreen->tabClosed( tab );
    this->mActiveTabs.removeAll( tab );
}

void TabManager::restoreTabs() {
    QSettings settings;
    int count = settings.beginReadArray( "tabs" );
    for ( int i = 0; i < count; ++i ) {
        settings.setArrayIndex( i );
        
        // get tab plugin name
        QString pluginName = settings.value( "plugin" ).toString();

        // get values to be passed on plugin constructor to recreate tab
        QVariant constructors = settings.value( "constructors" );

        // try recreating the tab
        WhaleTabBase * tab = this->mPluginHandler->recreateTab( pluginName, constructors );
        if ( tab == NULL ) {
            continue;
        }

        // add it to the list of tabs and display it
        this->addTab( tab );
    }
    settings.endArray();
}


// save the tabs to restore them later (on next start)
void TabManager::saveTabs() { // the parameter should be member
    QSettings settings;
    settings.remove( "tabs" );

    settings.beginWriteArray( "tabs", this->mActiveTabs.count() );
    for ( int i = 0; i < this->mActiveTabs.count(); ++i ) {
        WhaleTabBase * tab = this->mActiveTabs[ i ];
        settings.setArrayIndex( i );
        settings.setValue( "plugin", tab->plugin()->name() );
        settings.setValue( "constructors", tab->plugin()->constructors( tab ) );
    }
    settings.endArray();
}
